package be.kuleuven.thesis.pages;

import java.util.HashMap;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ToggleButton;
import be.kuleuven.thesis.R;
import be.kuleuven.thesis.framework.Atmosphere;
import be.kuleuven.thesis.framework.Filter;
import be.kuleuven.thesis.status.PlaylistGenerator;
import be.kuleuven.thesis.widget.RangeSeekBar;
import be.kuleuven.thesis.widget.RangeSeekBar.OnRangeSeekBarChangeListener;

public class SetRadioFilters extends Activity{
	private Filter filter;
	private PlaylistGenerator generator;
	Map<Atmosphere, ToggleButton> atmoButtons;
	RangeSeekBar<Integer> timeBar;
	RangeSeekBar<Integer> tempoBar;
	RangeSeekBar<Integer> popularityBar;
	RangeSeekBar<Integer> hardnessBar;
	Resources resources;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_radio_filters);
        generator = PlaylistGenerator.getInstance();
        resources = getResources();
        atmoButtons = new HashMap<Atmosphere, ToggleButton>();
        fillAtmoButtons();
        
        filter = generator.getFilter().clone();
        
        handleButtons();
        handleAtmospheres();
        handleTimeLayout();
        handleTempoLayout();
        handlePopularityLayout();
        handleHardnessLayout();
        setStateToFilter();
	}
	
	private void fillAtmoButtons() {
		ToggleButton cosy = (ToggleButton) findViewById(R.id.gezellig);
		atmoButtons.put(Atmosphere.COSY, cosy);
		ToggleButton cheerful = (ToggleButton) findViewById(R.id.opgewekt);
		atmoButtons.put(Atmosphere.CHEERFUL, cheerful);
		ToggleButton energetic = (ToggleButton) findViewById(R.id.energetisch);
		atmoButtons.put(Atmosphere.ENERGETIC, energetic);
		ToggleButton exuberant = (ToggleButton) findViewById(R.id.uitbundig);
		atmoButtons.put(Atmosphere.EXUBERANT, exuberant);
		ToggleButton fantastical = (ToggleButton) findViewById(R.id.fantasierijk);
		atmoButtons.put(Atmosphere.FANTASTICAL, fantastical);
		ToggleButton happy = (ToggleButton) findViewById(R.id.vrolijk);
		atmoButtons.put(Atmosphere.HAPPY, happy);
		ToggleButton mysterious = (ToggleButton) findViewById(R.id.mysterieus);
		atmoButtons.put(Atmosphere.MYSTERIOUS, mysterious);
		ToggleButton relax = (ToggleButton) findViewById(R.id.relax);
		atmoButtons.put(Atmosphere.RELAX, relax);
		ToggleButton romantic = (ToggleButton) findViewById(R.id.romantisch);
		atmoButtons.put(Atmosphere.ROMANTIC, romantic);
		ToggleButton serene = (ToggleButton) findViewById(R.id.rustig);
		atmoButtons.put(Atmosphere.SERENE, serene);
		ToggleButton stimulating = (ToggleButton) findViewById(R.id.stimulerend);
		atmoButtons.put(Atmosphere.STIMULATING, stimulating);
	}
	
	@Override
	public void onResume() {
		super.onResume();
//		filter = generator.getFilter().clone();
//        setStateToFilter();
	}
	
	private void handleButtons() {
		Button reset = (Button) findViewById(R.id.reset_filters);
		reset.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				filter.reset();
				setStateToFilter();
			}
		});
		
		Button cancel = (Button) findViewById(R.id.cancel_filters);
		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				filter = generator.getFilter();
				setStateToFilter();
				returnToCurrentPlaylist();
			}
		});
		
		Button apply = (Button) findViewById(R.id.apply_filters);
		apply.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				generator.setFilter(filter);
				returnToCurrentPlaylist();
			}
		});
	}
	
	private void handleAtmospheres() {
		for(Atmosphere a: Filter.ATMOSPHERES) {
			ToggleButton button = atmoButtons.get(a);
			button.setTag(a);
			button.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Atmosphere a = (Atmosphere) v.getTag();
					if(filter.getAtmospheres().contains(a))
						filter.removeAtmosphere(a);
					else filter.addAtmosphere(a);
				}
			});
		}
		
		ToggleButton allButton = (ToggleButton) findViewById(R.id.all_atmospheres);
		allButton.setTag(allButton);
		allButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ToggleButton allButton = (ToggleButton) v.getTag();
				if(allButton.isChecked()) {
					switchAllButtons(true);
					filter.setAtmospheres(filter.getAllAtmospheres());
				}
				else {
					switchAllButtons(false);
					filter.getAtmospheres().clear();
				}
			}
		});
	}
	
	private void switchAllButtons(boolean flag) {
		for(Atmosphere a: Filter.ATMOSPHERES) {
			ToggleButton button = atmoButtons.get(a);
			button.setChecked(flag);
		}
	}
	
	private void returnToCurrentPlaylist() {
		Intent i = new Intent(SetRadioFilters.this, CurrentPlaylist.class);
		View view = CurrentPlaylistGroup.group.getLocalActivityManager()
		        		.startActivity("Set Radio Filters", i
		        		.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
		        		.getDecorView();
		CurrentPlaylistGroup.group.replaceView(view);
	}
	
	private void setStateToFilter() {
//		switchAllButtons(false);
//		for(Atmosphere a: filter.getAtmospheres()) {
//			ToggleButton button = atmoButtons.get(a);
//			button.setChecked(true);
//		}
		timeBar.setSelectedMinValue(filter.getMinYear());
		timeBar.setSelectedMaxValue(filter.getMaxYear());
		tempoBar.setSelectedMinValue(filter.getMinTempo());
		tempoBar.setSelectedMaxValue(filter.getMaxTempo());
		popularityBar.setSelectedMinValue(filter.getMinPop());
		popularityBar.setSelectedMaxValue(filter.getMaxPop());
		hardnessBar.setSelectedMinValue(filter.getMinHard());
		hardnessBar.setSelectedMaxValue(filter.getMaxHard());
	}
	
	private void handleTimeLayout() {
		TextView yearLabel = (TextView) findViewById(R.id.year_label);
		String min = (String) (filter.getMinYear() == 1949 ? "...." : filter.getMinYear()+"");
		yearLabel.setText(resources.getString(R.string.period)+min+" - "+filter.getMaxYear());
		
		final Handler timeHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView yearLabel = (TextView) findViewById(R.id.year_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	String minString = (String) (min == 1949 ? "...." : min+"");
        		yearLabel.setText(resources.getString(R.string.period)+minString+" - "+max);
//            	if(min == Filter.MIN_YEAR && max == Filter.MAX_YEAR)
//            		yearLabel.setText("Period: All Times");
//            	else if(min == Filter.MIN_YEAR)
//            		yearLabel.setText("Period: Untill "+max);
//            	else if(max == Filter.MAX_YEAR)
//            		yearLabel.setText("Period: From "+min);
//            	else yearLabel.setText("Period: From "+min+" untill "+max);
            }
        };
        
        // create RangeSeekBar as Integer range between 20 and 75
        timeBar = new RangeSeekBar<Integer>(Filter.MIN_YEAR, Filter.MAX_YEAR, this, R.drawable.timebar2, timeHandler);
        timeBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                        filter.setMinYear(minValue);
                        filter.setMaxYear(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.year_layout);
        layout.addView(timeBar);
	}
	
	private void handleTempoLayout() {
		TextView tempoLabel = (TextView) findViewById(R.id.tempo_label);
    	tempoLabel.setText(resources.getString(R.string.tempo)+filter.getMinTempo()+"bpm - "+filter.getMaxTempo()+"bpm");
    	
		final Handler tempoHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView tempoLabel = (TextView) findViewById(R.id.tempo_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	tempoLabel.setText(resources.getString(R.string.tempo)+min+"bpm - "+max+"bpm");
            }
        };
        
		// create RangeSeekBar as Integer range between 20 and 75
        tempoBar = new RangeSeekBar<Integer>(Filter.MIN_TEMPO, Filter.MAX_TEMPO, this, 0, tempoHandler);
        tempoBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                        filter.setMinTempo(minValue);
                        filter.setMaxTempo(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.tempo_layout);
        layout.addView(tempoBar);
	}
	
	private void handlePopularityLayout() {
		TextView popularityLabel = (TextView) findViewById(R.id.popularity_label);
    	popularityLabel.setText(resources.getString(R.string.popularity)+filter.getMinPop()+" - "+filter.getMaxPop());
    	
		final Handler popularityHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView popularityLabel = (TextView) findViewById(R.id.popularity_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	popularityLabel.setText(resources.getString(R.string.popularity)+" "+min+" - "+max);
            }
        };
        
		// create RangeSeekBar as Integer range between 20 and 75
        popularityBar = new RangeSeekBar<Integer>(Filter.MIN_POP, Filter.MAX_POP, this, 0, popularityHandler);
        popularityBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                        filter.setMinPop(minValue);
                        filter.setMaxPop(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.popularity_layout);
        layout.addView(popularityBar);
	}
	
	private void handleHardnessLayout() {
		TextView hardnessLabel = (TextView) findViewById(R.id.hardness_label);
    	hardnessLabel.setText(resources.getString(R.string.hardness)+filter.getMinHard()+" - "+filter.getMaxHard());
    	
		final Handler hardnessHandler = new Handler() {
            @Override
            public void handleMessage(Message message) {
            	TextView hardnessLabel = (TextView) findViewById(R.id.hardness_label);
            	int min = message.arg1;
            	int max = message.arg2;
            	hardnessLabel.setText(resources.getString(R.string.hardness)+" "+min+" - "+max);
            }
        };
        
		// create RangeSeekBar as Integer range between 20 and 75
        hardnessBar = new RangeSeekBar<Integer>(Filter.MIN_HARD, Filter.MAX_HARD, this, 0, hardnessHandler);
        hardnessBar.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Integer>() {
                @Override
                public void rangeSeekBarValuesChanged(Integer minValue, Integer maxValue) {
                        filter.setMinPop(minValue);
                        filter.setMaxPop(maxValue);
                }
        });

        // add RangeSeekBar to pre-defined layout
        ViewGroup layout = (ViewGroup) findViewById(R.id.hardness_layout);
        layout.addView(hardnessBar);
	}

}
